//package org.example.config;
//
//import com.alibaba.nacos.api.NacosFactory;
//import com.alibaba.nacos.api.exception.NacosException;
//import com.alibaba.nacos.api.naming.NamingService;
//import com.alibaba.nacos.api.naming.pojo.Instance;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.stereotype.Component;
//import javax.annotation.PostConstruct;
//import javax.annotation.PreDestroy;
//
//
///**
// * @Author wangjun
// * @Date 2025/3/18 19:14
// */
//@Component
//public class NacosRegistration {
//    @Value("${nacos.server-addr}")
//    private String nacosServerAddr;
//
//    @Value("${nacos.service.name}")
//    private String serviceName;
//
//    @Value("${nacos.service.port}")
//    private int port;
//
//    private NamingService namingService;
//
//    // 应用启动时注册服务
//    @PostConstruct
//    public void register() throws NacosException {
//        namingService = NacosFactory.createNamingService(nacosServerAddr);
//        Instance instance = new CloseableThreadContext.Instance();
//        instance.setIp(getLocalIp());  // 获取本机 IP
//        instance.setPort(port);
//        instance.setServiceName(serviceName);
//        instance.setClusterName("DEFAULT");
//        namingService.registerInstance(serviceName, instance);
//        System.out.println("Service registered to Nacos: " + serviceName);
//    }
//
//    // 应用关闭时注销服务
//    @PreDestroy
//    public void deregister() throws NacosException {
//        if (namingService != null) {
//            namingService.deregisterInstance(serviceName, getLocalIp(), port);
//            System.out.println("Service deregistered from Nacos: " + serviceName);
//        }
//    }
//
//    // 获取本机 IP（简化示例）
//    private String getLocalIp() {
//        try {
//            return InetAddress.getLocalHost().getHostAddress();
//        } catch (UnknownHostException e) {
//            return "127.0.0.1";
//        }
//    }
//}
